﻿#region License
/* Copyright (C) 2009 Tim Coulter
 * 
 * This file is part of ExtremeML.
 * 
 * ExtremeML is free software: you can redistribute
 * it and/or modify it under the terms of the GNU General Public
 * License, as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 * 
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
 * the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see http://www.gnu.org/licenses/.
*/
#endregion

using DocumentFormat.OpenXml.Spreadsheet;

namespace ExtremeML.Spreadsheet
{
	// This is a partial class that adds custom functionality to its auto-generated partner.
	public sealed partial class TableColumnWrapperCollection
	{
		#region Custom Properties

		private const string DefaultItemNamePrefix = "Column";

		/// <summary>
		/// Gets the containing <see cref="TableWrapper"/>.
		/// </summary>
		public TableWrapper Table
		{
			get { return (TableWrapper)Parent.Parent; }
		}

//ToDo: This should be implemented as the UniquelyNamedCollectionPattern
		/// <summary>
		/// Gets a <see cref="TableColumnWrapper"/> by the name of its wrapped <see cref="TableColumn"/>.
		/// </summary>
		public TableColumnWrapper this[string name]
		{
			get { return Items.Find(item => item.Name == name); }
		}

		#endregion
		#region Custom Methods

		/// <summary>
		/// Adds a new table column wrapper to the collection at the specified column index.
		/// </summary>
		/// <param name="index">The table-relative zero-based index of the column to add.</param>
		/// <returns>A new <see cref="TableColumnWrapper"/> instance.</returns>
		internal TableColumnWrapper Add(
			int index)
		{
			var result = AddAt(index);
			result.Name = GetUniqueColumnName();
			return result;
		}

		#endregion
		#region Overrides


		#endregion
		#region Implementation Methods

		/// <summary>
		/// Returns a unique name for a new table column using a simpified variant of the equivalent Excel algorithm.
		/// </summary>
		private string GetUniqueColumnName()
		{
			var suffix = 0;

			while (true)
			{
				var name = DefaultItemNamePrefix + ++suffix;

				if (Items.Find(item => item.Name == name) == null)
				{
					return name;
				}
			}
		}

		#endregion
		#region Static Methods


		#endregion
	}
}
